package HTTP

import (
	"SQL/myDB"
	"database/sql"
	"logs"
	"net/http"
)

func dbPage(w http.ResponseWriter, req *http.Request) {
	printRequestInfo(req)
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	w.Write([]byte(`
<!DOCTYPE html>
<html>
<head>
<title>数据库所有数据</title>
</head>
<body>
	`))
	w.Write([]byte(`
	<a href="\setData?page=resetDB"><h1>重置数据</h1></a>
	<a href="\setData?page=copyDB"><h1>复制数据</h1></a>
	`))
	defer w.Write([]byte(`
</body>
</html>
	`))
	w.Write([]byte(`
	<h1>以下是数据库每个表前一百条，方便你们接口联调</h1>
	`))
	db, err := myDB.GetDB()
	if err != nil {
		w.Write([]byte("<p>" + err.Error() + "</p>"))
		return
	}

	description := []string{
		`1.objects(id int64 pk,nickname string,iconURL string,isUser bool,custom jsonb)
		`, `2.users(id int64 fk pk,account string unique,password string,isManager bool)
		`, `3.groups(id int64 fk pk,createtime time)
		`, `4.members(groupID int64 fk,userID int64 fk,pk(groupID,userID))
		`, `5.messages(id int64 pk,content string,sender int64 fk,receiver int64 fk,createTime time)
		`, `6.sessions(senderID int64 fk,receiverID  int64 fk,lastMsgID int64 fk,pk(senderID,receiverID))；
		`,
	}
	Sql := []string{
		`select * from objects
		`, `select * from users
		`, `select * from groups
		`, `select * from members
		`, `select * from messages
		`, `select * from sessions
		`,
	}
	for idx := 0; idx < len(Sql); idx++ {
		w.Write([]byte("<h2>" + description[idx] + "</h2>"))
		err := showData(w, db, Sql[idx])
		if err != nil {
			logs.Print("dbPage error:", err.Error())
			return
		}
	}
}

func showData(w http.ResponseWriter, db *sql.DB, Sql string) error {
	Sql += " limit 100"
	rows, err := db.Query(Sql)
	if err != nil {
		w.Write([]byte("<p>" + err.Error() + "</p>"))
		return err
	}
	defer rows.Close()

	w.Write([]byte(`
		<table border="1">
			<tr>
			`))
	defer w.Write([]byte(` 
			</tr>
		</table> `))

	cols, err := rows.Columns()
	if err != nil {
		w.Write([]byte(err.Error()))
		return err
	}
	for _, val := range cols {
		w.Write([]byte("<th>" + val + "</th>"))
	}

	return htmlOutputRows(w, len(cols), rows)
}
func htmlOutputRows(w http.ResponseWriter, colNum int, rows *sql.Rows) error {
	str := make([][]byte, colNum)
	for rows.Next() {
		w.Write([]byte(` <tr>`))
		args := make([]interface{}, 0)
		for idx := 0; idx < colNum; idx++ {
			args = append(args, &str[idx])
		}
		err := rows.Scan(args...)
		if err != nil {
			w.Write([]byte(err.Error()))
			return err
		}
		for _, val := range str {
			w.Write([]byte("<td>" + string(val) + "</td>"))
		}
		w.Write([]byte("</tr>"))
	}
	return nil
}
